﻿using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;

namespace NHibernate.Sidekick.Utils.Extensions
{
    /// <summary>
    /// Extension methods for the <see cref="string"/> type.
    /// </summary>
    public static class StringHelper
    {
        /// <summary>
        /// Formats the string from camelCase to Under_Score naming.
        /// </summary>
        /// <param name="textToSplit">The text to split.</param>
        /// <returns></returns>
        public static string ToUnderscoredNaming(this string textToSplit)
        {
            const string regexCamelCaseSplit = "(?<!^)(?=[A-Z])";
            var split = Regex.Split(textToSplit, regexCamelCaseSplit);
            var builder = new StringBuilder();
            foreach (var entry in split)
            {
                builder.AppendFormat("{0}_", entry);
            }

            var name = builder.ToString().TrimEnd('_');
            return name;
        }

        /// <summary>
        /// Truncates the specified text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="endIndex">The number of characters to contain.</param>
        /// <returns></returns>
        public static string Truncate(this string text, int endIndex)
        {
            if (text.Length > endIndex)
            {
                text = text.Substring(0, endIndex).TrimEnd('_');
            }
            return text;
        }

        /// <summary>
        /// Wraps a string with the specified character.
        /// </summary>
        /// <param name="text">The string to wrap.</param>
        /// <param name="wrapper">The character used to wrap.</param>
        /// <returns></returns>
        public static string WrapInCharacter(this string text, char wrapper)
        {
            return string.Format(CultureInfo.CurrentCulture, @"{0}{1}{0}", wrapper, text);
        }
    }
}
